app.controller('HospitalController', HositalController);
app.factory('HospitalFactory', HospitalFactory);
app.factory('OperationTimeFactory', OperationTimeFactory);
function OperationTimeFactory(RESTService) {
    var object = {};
    object.createOperationTime = function (item) {
        return RESTService.postResponse("/rest/opecentime/createOpeCenTime?", item)
    };
    object.finishOperationTime = function (param) {
        return RESTService.postResponse("/rest/opecentime/finish?", param);
    };
    object.getActiveOperationTimes = function (param) {
        return RESTService.getResponse("/rest/opecentime/getActiveOpeCenTimes?" + $.param(param));
    };
    object.getFinishedOperationTimes = function (param) {
        return RESTService.getResponse("/rest/opecentime/getFinishedOpeCenTimes?" + $.param(param));
    };
    object.getFinishedOperationTimeCount = function (param) {
        return RESTService.getResponse("/rest/opecentime/getFinishedOpeCenTimesCount?" + $.param(param));
    };
    object.getOpeCenTime = function (param) {
        return RESTService.getResponse("/rest/opecentime/getOpeCenTime?" + $.param(param));
    };
    object.getOpeCenTimes = function (param) {
        return RESTService.getResponse("/rest/opecentime/getOpeCenTimes?" + $.param(param));
    };
    object.SetOpen = function (param) {
        return RESTService.getResponse("/rest/opecentime/open?" + $.param(param));
    };
    object.SetDate = function (param) {
        return RESTService.postResponse("/rest/opecentime/setDate?", param);
    };
    object.SetSurgeon = function (param) {
        return RESTService.postResponse("/rest/opecentime/setSurgeon?", param);
    };
    return object;
}
function HospitalFactory(RESTService) {
    var object = {};

    function filterValue(val, type) {
        var res = null;
        switch (type) {
            case "string":
                res = (val) ? val.trim() : "";
                break;
            case "number":
            case "long":
                res = (val) ? val : null;
                break;
            case "date":
                res = (val) ? val : new Date();
                break;
            default:
        }
        return res;
    }

    object.SetHospital = function (item) {
        var hosp = {
            hosp_Id: filterValue(item.hosp_Id, "long"),
            hosp_Cn_Name: filterValue(item.hosp_Cn_Name, "string"),
            hosp_En_Name: filterValue(item.hosp_En_Name, "string"),
            hosp_Desc: filterValue(item.hosp_Desc, "string"),
            _country: item._country,
            country_Id: filterValue(item.country_Id, "long"),
            hospLevel: item.hospLevel,
            hospLevel_Id: filterValue(item.hospLevel_Id, "long"),
            _province: item._province,
            province_Id: filterValue(item.province_Id, "long"),
            city_Id: filterValue(item.city_Id, "long"),
            _city: item._city,
            county_Id: filterValue(item.county_Id, "long"),
            _county: item._county,
            isOpeCenter: (item.opeCenter == null) ? false : item.opeCenter,
            orderBy: filterValue(item.orderBy, "long"),
            updated: filterValue(item.updated, "date"),
            isedit: false
        };
        hosp.isOpeCenterFlag = hosp.isOpeCenter;
        if (hosp.hosp_Id == 0) // is New
        {
            hosp.isNew = true;
            hosp.isedit = true;
        }
        return hosp;
    };
    object.getCount = function (param) {
        return RESTService.getResponse("/rest/hosp/getHospsCount?" + $.param(param));
    };
    object.getPage = function (param) {
        return RESTService.getResponse("/rest/hosp/getHosps?" + $.param(param));
    };
    object.getOne = function (param) {
        return RESTService.getResponse("/rest/hosp/getHosp?" + $.param(param));
    };
    object.saveHospital = function (item) {
        if (item.hosp_Id > 0) {
            return RESTService.postResponse("/rest/hosp/updateHosp?", item)
        } else {
            return RESTService.postResponse("/rest/hosp/createHosp?", item)
        }
    };
    object.deleteOperationCenter = function (param) {
        return RESTService.postResponse("/rest/hosp/deleteHosp?", param);
    };
    return object;
}
function HositalController($rootScope, $scope, $modal, HospitalFactory, RESTService, $compile, AuthService, $http, $stateParams) {
    $rootScope.ifSubmit = 'no';
    $scope.optionFilter = {
        hospLevel_Id: 0,
        province_Id: 0,
        country_Id: 38,
        county_Id: 0,
        city_Id: 0
    };
    $scope.cacheNewHospital = {};
    $scope.filterOpe = $stateParams.filterOpe;
    console.log('$scope.filterOpe', $scope.filterOpe);
    // define value
    $scope.Hospital = null;
    $scope.ArrHospital = [];
    $scope.ArrCountry = [];
    $scope.ArrProvince = [];
    $scope.ArrCity = [];
    $scope.ArrCounty = [];
    $scope.ArrHospLevel = [];
    // get hospital with pagination
    $scope.dtOptions = {
        aaSorting: [],
        bFilter: false,
        bLengthChange: false,
        bSort: false,
        bStateSave: false,
        oLanguage: {
            sUrl: ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
        },
        processing: true,
        serverSide: true,
        sAjaxDataProp: "data",
        ajax: function (data, callback) {
            $scope.ArrHospital = [];
            getCount();
            // prepare query variables
            var params = {
                hospLevel_Id: $scope.optionFilter.hospLevel_Id,
                province_Id: $scope.optionFilter.province_Id,
                country_Id: $scope.optionFilter.country_Id,
                county_Id: $scope.optionFilter.county_Id,
                city_Id: $scope.optionFilter.city_Id,
                hosp_Name: $scope.optionFilter.hosp_Name,
                flag: $scope.filterOpe,
                pageNo: data.start / data.length + 1,
                pageSize: data.length
            };
            var sort = [], i;

            if (0 !== data.order.length) {
                for (i in data.order) {
                    if (data.order.hasOwnProperty(i)) {
                        sort.push({
                            property: data.columns[data.order[i].column].data,
                            direction: data.order[i].dir.toUpperCase()
                        });
                    }
                }

                if (0 !== sort.length) {
                    params.sort = angular.toJson(sort);
                }
            }

            if (3 <= data.search.value.length) {
                params.filter = data.search.value;
            }
            // transmit to server
            HospitalFactory.getPage(params).then(
                function (response) {
                    $scope.ArrHospital = [];
                    angular.forEach(response, function (item) {
                        var hosp = HospitalFactory.SetHospital(item);
                        hosp.No = $scope.ArrHospital.length + (params.pageNo * params.pageSize) - 9;
                        $scope.ArrHospital.push(hosp);
                    });
                    callback({
                        aaData: [],
                        draw: data.draw,
                        recordsTotal: $scope.rowCount,
                        recordsFiltered: $scope.rowCount
                    });
                    $scope.dtInstance.find("td.dataTables_empty").parent().hide(); // small hack for "aaData: []"
                    // console.log('12345678900987654:',response);
                });
        },
        type: 'POST',
        dateType: 'json',
        fnCreatedRow: function (row) {
            $compile(row)($scope);
        },
        fnInitComplete: function () {
            $scope.$parent.dtInstance = this.fnSetFilteringDelay();
        }
    };
    // action list
    function getCount() {
        var params = {
            hospLevel_Id: $scope.optionFilter.hospLevel_Id,
            province_Id: $scope.optionFilter.province_Id,
            country_Id: $scope.optionFilter.country_Id,
            county_Id: $scope.optionFilter.county_Id,
            city_Id: $scope.optionFilter.city_Id,
            hosp_Name: $scope.optionFilter.hosp_Name,
            flag: $scope.filterOpe
        };
        // if ($scope.filterOpe) {
        //     console.log($scope.filterOpe);
        //     params.flag = true;//显示手术中心
        // }
        HospitalFactory.getCount(params).then(function (response) {
            if (undefined !== response) {
                $scope.rowCount = response[0].count;
            }
        });
    }

    function reloadData() {
        $scope.dtInstance.DataTable().ajax.reload();
    }

    $scope.getHospitalLevels = function () {
        var params = {};
        RESTService.getResponse("/rest/hosplevel/getHospLevels?" + $.param(params), null, null).then(function (response) {
            if (undefined !== response) {
                angular.forEach(response, function (arrays) {
                    $scope.ArrHospLevel.push(arrays);
                });
            }
        });
    };
    $scope.getCountries = function () {
        var params = {};
        RESTService.getResponse("/rest/country/getCountryList?" + $.param(params), null, null).then(function (response) {
            if (undefined !== response) {
                angular.forEach(response, function (arrays) {
                    $scope.ArrCountry.push(arrays);
                });
            }
        });
    };
    $scope.getProvinces = function (item) {
        // console.log('修改了国家！');
        $scope.onChangeCountry(item);
        if (item.country_Id != null && item.country_Id > 0) {
            var params = {country_Id: item.country_Id};
            $scope.optionFilter.city_Id = 0;
            $scope.optionFilter.county_Id = 0;
            RESTService.getResponse("/rest/location/getProvinceList?" + $.param(params), null, null).then(function (response) {
                if (undefined !== response) {
                    $scope.ArrProvince = response;
                }
            });
        }
    };
    $scope.getCities = function (item) {
        // console.log('修改了省！');
        if (item.city_Id == null || item.city_Id == "") {
            $scope.onChangeProvince(item);
        }
        if (item.province_Id != null && item.province_Id > 0) {
            var params = {province_Id: item.province_Id};
            $scope.optionFilter.county_Id = 0;
            RESTService.getResponse("/rest/location/getCityList?" + $.param(params), null, null).then(function (response) {
                if (undefined !== response) {
                    $scope.ArrCity = response;
                }
            });
        }
    };
    $scope.getCounties = function (item) {
        // console.log('修改了市！');
        if (item.county_Id == null || item.county_Id == "") {
            $scope.onChangeCity(item);
        }
        if (item.city_Id != null && item.city_Id > 0) {
            var params = {city_Id: item.city_Id};
            RESTService.getResponse("/rest/location/getCountyList?" + $.param(params), null, null).then(function (response) {
                if (undefined !== response) {
                    $scope.ArrCounty = response;
                }
            });
        }
    };
    $scope.getHospital = function (id) {
        var params = {
            hosp_Id: id
        };
        HospitalFactory.getOne(params).then(function (response) {
            if (undefined !== response) {
                angular.forEach(response, function (item) {
                    var hosp = HospitalFactory.SetHospital(item);
                    $scope.Hospital = hosp;
                });
            }
        });
    };
    $scope.open = function (attrs, data) {
        var modalInstance = $modal.open(angular.extend({
            backdrop: 'static',
            controller: "ModalInstanceCtrl",
            resolve: {
                items: function () {
                    return Object(data);
                }
            }
        }, attrs));

        modalInstance.result.then(function () {
            if (data.editmode == "New") {
                setCache(data);
            }
            reloadData();
        }, function () {
        })
    };

    function setCache(item) {
        $scope.cacheNewHospital = {
            hospLevel_Id: item.hospLevel_Id,
            country_Id: item.country_Id,
            province_Id: item.province_Id,
            city_Id: item.city_Id,
            county_Id: item.county_Id
        };
    }

    $scope.newHospital = function (attrs) {
        $rootScope.ifSubmit = 'no';
        var item = HospitalFactory.SetHospital($scope.cacheNewHospital);
        item.country_Id = 38;
        item.province_Id = item.city_Id = item.county_Id = item.hospLevel_Id = '';
        item.isedit = true;
        item.editmode = "New";
        $scope.open(attrs, item);
    };
    $scope.iseditHosp = function (item) {
        item.isedit = true;
    };
    $scope.editHospital = function (attrs, item) {
        item.isedit = true;
        $scope.open(attrs, item);
    };
    $scope.saveHospital = function (item) {
        if ($rootScope.ifSubmit == 'no') {
            $rootScope.ifSubmit = 'yes';
            var params = {
                hosp_Cn_Name: item.hosp_Cn_Name,
                hosp_En_Name: item.hosp_En_Name,
                hosp_Desc: item.hosp_Desc,
                hospLevel_Id: item.hospLevel_Id,
                country_Id: item.country_Id,
                province_Id: item.province_Id,
                city_Id: item.city_Id,
                county_Id: item.county_Id,
                isOpeCenter: item.isOpeCenter,
                access_token: RESTService.getAccess_Token()
            };
            // if(item.hosp_Id > 0){
            //     params.hosp_Id = item.hosp_Id;
            // }

            /*
             if(item.hosp_Id > 0){
             params.hosp_Id = item.hosp_Id;
             $http.post(AuthService.getRsContext() + "/rest/hosp/updateHosp?" + $.param(params)).then(function(response){
             console.log(response);
             if (undefined !== response) {
             console.log('response:',response);
             item.hosp_Id = response.data.data[0].hosp_Id;
             item.isOpeCenterFlag = item.isOpeCenter;
             item.isedit = false;
             $scope.ok();
             }
             });
             }else{
             $http.post(AuthService.getRsContext() + "/rest/hosp/createHosp?" + $.param(params)).then(function(response){
             console.log(response);
             if (undefined !== response) {
             console.log('response:',response);
             item.hosp_Id = response.data.data[0].hosp_Id;
             item.isOpeCenterFlag = item.isOpeCenter;
             item.isedit = false;
             $scope.ok();
             }
             });
             }
             */
            if (item.hosp_Id > 0) {
                params.hosp_Id = item.hosp_Id;
            }
            HospitalFactory.saveHospital(params).then(function (response) {
                if (undefined !== response) {
                    console.log('response:', response);
                    item.hosp_Id = response[0].hosp_Id;
                    item.isOpeCenterFlag = item.isOpeCenter;
                    item.isedit = false;
                    $scope.ok();
                }
            });
        }

    };

    $scope.openDeleteHospitalPopup = function (hosp) {
        var modalInstance = $modal.open({
            backdrop: 'static',
            templateUrl: 'deletePopup.html',
            controller: 'ModalInstanceCtrl',
            size: 'md',
            resolve: {
                items: function () {
                    return hosp;
                }
            }
        });
        modalInstance.result.then(function () {
            $scope.deleteHospital(hosp);
            //ok click
        }, function () {

        })
    }

    $scope.deleteHospital = function (item) {
        if (item.hosp_Id > 0) {
            var params = {
                hosp_Id: item.hosp_Id
            };
            HospitalFactory.deleteOperationCenter(params).then(function (response) {
                if(response[0] && response[0].result === 'true'){
                    var bodyText = $rootScope.locale == 'Cn' ? '\u0020\u533b\u9662\u5220\u9664\u6210\u529f' : 'Hospital deleted successfully';
                    RESTService.pop("success", "", bodyText);
                }
                reloadData();
            });
        }

    };
    $scope.onChangeCountry = function (item) {
        if (item.country_Id != 38 || item.country_Id == 0) {
            item.city_Id = item.province_Id = item.county_Id = '';
        }
    };
    $scope.onChangeProvince = function (item) {
        item.city_Id = item.county_Id = '';

    };
    $scope.onChangeCity = function (item) {
        item.county_Id = '';
    };
    $scope.assignOpeCent = function (item) {
        item.isOpeCenter = true;
        $scope.saveHospital(item);
    };
    $scope.isFilterOpeCent = function (flag) {
        $scope.filterOpe = flag;
        reloadData()
    };
    $scope.isFilterOption = function () {
        $scope.isShowFilterOption = !$scope.isShowFilterOption;
        if (true == $scope.isShowFilterOption && 0 == $scope.ArrCountry.length && 0 == $scope.ArrProvince.length) {
            $scope.getCountries();
            $scope.getProvinces($scope.optionFilter);
            $scope.getHospitalLevels();
        }
    };
    $scope.startSearch = function () {
        reloadData();
    };
    $scope.resetFilter = function () {
        $scope.optionFilter = {
            hospLevel_Id: 0,
            province_Id: 0,
            country_Id: 0,
            county_Id: 0,
            city_Id: 0
        };
    }
};

